import { defineStore } from 'pinia'
import { request } from '@/utils/request'
import { NETWORK_CONFIG } from '@/config/network.js'

interface UserProfile {
  uid: string | number;
  nickname: string;
  avatarUrl: string;
  signature?: string;
  creditScore?: number;
  phone?: string;
  email?: string;
  orgName?: string;
  orgAvatarUrl?: string;
  // ...其他可能字段
}

export const useUserStore = defineStore('user', {
  state: () => ({
    token: uni.getStorageSync('accessToken') || '',
    profile: null as UserProfile | null,
    isInitialized: false
  }),

  getters: {
    isLoggedIn: (state) => !!state.token && !!state.profile,
    getUserInfo: (state) => state.profile
  },

  actions: {
    // 初始化用户状态
    async initialize() {

      if (this.isInitialized) {
        console.log('用户状态已初始化')
        return
      }

      console.log('开始初始化用户状态...')
      const token = uni.getStorageSync('accessToken')
      
      if (!token) {
        console.log('未找到 token，用户未登录')
        this.isInitialized = true
        
        this.gotoLogin();
        return
      }

      try {
        await this.fetchUserProfile()
        console.log('用户状态初始化完成')
      } catch (error) {
        console.error('初始化用户状态失败:', error)
        // 不清除用户状态，避免后端 500 时被强制登出
      } finally {
        this.isInitialized = true
      }
    },

    // 获取用户信息
    async fetchUserProfile() {
      console.log('开始获取用户信息...')
      try {
        console.log(this.token)
        if (!this.token) throw new Error('Token 不存在')
        console.log(this.token)
        const res: any = await (uni.request({
          url: `${NETWORK_CONFIG.API_BASE_URL}/user/me`,
          method: 'POST',  // 改回POST，因为服务器返回405表示不支持GET
          header: {
            'Content-Type': 'application/json', 
            'Access-Token': `Bearer ${this.token}`
          },
          // 如果需要，可以添加空请求体
          data: {} // uni.request 不支持 timeout 属性
        }) as any)

        console.log("=== 用户信息API响应完整信息 ===");
        console.log("响应状态码:", res?.statusCode);
        console.log("响应头信息:", res?.header);
        console.log("响应数据:", res?.data);
        console.log("响应数据类型:", typeof res?.data);
        console.log("响应数据是否为数组:", Array.isArray(res?.data));
        console.log("响应数据键名:", res?.data ? Object.keys(res?.data) : '无数据');
        console.log("返回内容JSON字符串:", JSON.stringify(res));
        console.log("=================================");

        const status = res?.statusCode
        if (status === 200) {
          const raw = res.data
          let data: any
          
          console.log("=== 用户数据解析过程 ===");
          console.log("原始响应数据类型:", typeof raw)
          console.log("原始响应数据:", raw)
          console.log("原始响应数据是否为null:", raw === null)
          console.log("原始响应数据是否为undefined:", raw === undefined)
          console.log("原始响应数据是否为字符串:", typeof raw === 'string')
          console.log("原始响应数据长度:", raw ? (typeof raw === 'string' ? raw.length : Object.keys(raw).length) : 0)
          
          if (typeof raw === 'string') {
            try { 
              data = JSON.parse(raw) 
              console.log("解析JSON后:", data)
            } catch (e) { 
              console.error("JSON解析失败:", e)
              data = null 
            }
          } else {
            data = raw
          }
          
          // 判定无效数据或业务提示token异常，统一跳转登录
          const msg = String(data?.message || '').toLowerCase()
          const tokenInvalid = msg.includes('token') && (msg.includes('无效') || msg.includes('过期'))
          const missingUid = !data || typeof data !== 'object' || !data.uid
          if (tokenInvalid || missingUid) {
            console.warn('用户信息无效或token异常，跳转登录', { tokenInvalid, missingUid, data })
            this.clearUserState()
            this.gotoLogin()
            throw new Error('用户信息无效或未登录')
          }
          
          this.profile = data
          console.log('用户信息获取成功:', data)
          // 打印当前用户信息（格式化）
          this.debugPrintProfile()
          return data
        }

        if (status === 401 || status === 403) {
          console.log("=== 认证失败处理 ===");
          console.log("状态码:", status);
          console.log("响应数据:", res.data);
          console.log("清除用户状态并跳转登录页");
          // 仅未授权/禁止时清状态并跳转
          this.clearUserState()
          this.gotoLogin()
          throw new Error('未授权或无权限')
        }

        // 其他错误：统一清理并跳登录
        console.log("=== 其他错误处理（跳登录） ===");
        console.log("状态码:", status);
        console.log("响应数据:", res.data);
        this.clearUserState()
        this.gotoLogin()
        throw new Error(`获取用户信息失败: ${status}`)
      } catch (error: any) {
        console.log("=== 用户信息获取异常处理 ===");
        console.error('获取用户信息失败:', error)
        console.log("错误类型:", typeof error);
        console.log("错误消息:", error?.message || '无消息');
        console.log("错误堆栈:", error?.stack || '无堆栈');
        console.log("错误名称:", error?.name || '无名称');
        console.log("===============================");
        // 捕获到任何异常也跳转登录，满足“无法获取就跳登录”的需求
        this.clearUserState()
        this.gotoLogin()
        throw error
      }
    },

    // 设置用户信息
    setUser(profile: UserProfile) {
      this.profile = profile
      console.log('用户信息已更新:', profile)
      this.debugPrintProfile()
    },

    // 设置 token
    setToken(token: string) {
      this.token = token
      uni.setStorageSync('accessToken', token)
      console.log('Token 已更新')
    },

    // 登录
    async login(account: string, password: string) {
      console.log('开始登录...')
      try {
        const res = await request({
          url: `${NETWORK_CONFIG.API_BASE_URL}/auth/login`,
          method: 'POST',
          data: { account, password }
        })

        if (!res || !res.token) {
          throw new Error('登录失败')
        }

        this.setToken(res.token)
        await this.fetchUserProfile()
        console.log('登录成功')
        return res
      } catch (error) {
        console.error('登录失败:', error)
        this.clearUserState()
        throw error
      }
    },

    // 登出
    logout() {
      this.clearUserState()
      console.log('用户已登出')
    },


    
    // 清除用户状态
    clearUserState() {
      this.token = ''
      this.profile = null
      //uni.removeStorageSync('accessToken')
      console.log('用户状态已清除')
    },

    // 恢复用户状态（从本地存储）
    restoreUser() {
      const token = uni.getStorageSync('accessToken')
      if (token) {
        this.token = token
        console.log('Token 已从本地存储恢复')
      }
    },

    // 跳转到登录页的工具函数
   gotoLogin() {
    try {
      const pages = (globalThis as any).getCurrentPages?.()
      const current = pages && pages.length ? pages[pages.length - 1]?.route || '' : ''
      if (current.includes('pages/auth/login/index')) return
    } catch {}
    if ((uni as any).__gotoLoginLock__) return
    ;(uni as any).__gotoLoginLock__ = true
    uni.redirectTo({
      url: '/pages/auth/login/index',
      success: () => { (uni as any).__gotoLoginLock__ = false },
      fail: () => { (uni as any).__gotoLoginLock__ = false }
    })
  }
  ,
  // 调试：打印当前用户信息
  debugPrintProfile() {
    try {
      console.log('=== 当前用户信息 ===')
      console.log('Token 存在:', !!this.token)
      if (this.profile) {
        const { uid, nickname, avatarUrl, phone, email, orgName } = this.profile as any
        console.table([{ uid, nickname, avatarUrl, phone, email, orgName }])
        console.log('完整profile:', JSON.stringify(this.profile, null, 2))
      } else {
        console.log('profile 为空')
      }
      console.log('====================')
    } catch (e) {
      console.log('打印用户信息失败', e)
    }
  }
  }
}) 